package com.kpl.kplstzble.fragment;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.kpl.kplstzble.R;
import com.kpl.kplstzble.entity.HistoryData;
import com.kpl.kplstzble.utils.DBUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class DataDetailFragment extends Fragment implements CompoundButton.OnCheckedChangeListener, LocationSource, AMapLocationListener {
    private MapView mapView;
    private View mapLayout;
    private AMap aMap;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption clientOption;
    private TextView showarea;
    private TextView distance;
    private TextView speed;
    private TextView time;
    private List<LatLng> latLngs = new ArrayList<>();
    private static HistoryData historyData;
    private ToggleButton btn_mapchange;
    //登录按钮
    private Button btn_delete;
    DataDetailFragment(HistoryData historyData0){
        historyData=historyData0;
        System.out.println(historyData0.getMunum());
    }
    public void refresh(){
        Toolbar toolbar = mapLayout.findViewById(R.id.toolbar);
        //设置图标
        //在android studio里面创建图标会放到mipmap下
        //如果是自己做的放在drawable下面的就是R.drawable.xxxx
        toolbar.setNavigationIcon(R.mipmap.back1);
           /* setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
        toolbar.setNavigationOnClickListener(view -> {
            HistoryDataFragment historyDataFragment = new HistoryDataFragment();
            FragmentManager fm = getActivity().getSupportFragmentManager();
                    /*fm.beginTransaction()
                            .replace(R.id.fl_content, dataDetailFragment)
                            .commit();*/
            fm.beginTransaction().replace(R.id.fl_content,historyDataFragment)
                    .commit();
            //getActivity().finish();
        });
        btn_mapchange= mapLayout.findViewById(R.id.btn_mapchange);
        btn_mapchange.setOnCheckedChangeListener(this);
        showarea= mapLayout.findViewById(R.id.showarea);
        distance= mapLayout.findViewById(R.id.distance);
        speed= mapLayout.findViewById(R.id.speed);
        time= mapLayout.findViewById(R.id.time);
        btn_delete=  mapLayout.findViewById(R.id.btn_delete);
        showarea.setText("面积："+historyData.getMunum()+"亩");
        distance.setText("距离："+historyData.getDistance()+"米");
        double v = BigDecimal.valueOf(6 * Double.parseDouble(historyData.getDistance()) / 100 / Integer.parseInt(historyData.getDatediffer())).setScale(1, BigDecimal.ROUND_DOWN).doubleValue();
        speed.setText("平均速度："+v+"km/h");
        time.setText("时间："+historyData.getDatediffer()+"分");
        btn_delete.setOnClickListener(view -> new Thread(() -> {
                DBUtils.deleteonedata(historyData.getId());
                Message msg= new Message();
                msg.what=0;
                //msg.obj=gethistorydata;
                //Handler.sendMessage(msg);
            }
        ).start());

        String datainfo = historyData.getDatainfo();
        datainfo = datainfo.replace("[", "").replace("]", "");
        String[] datainfosplit = datainfo.split(",");
        Double lat = null;
        Double lon = null;
        for (int i=0;i<datainfosplit.length;i++) {
            String[] split = datainfosplit[i].split("&");
            LatLng latLng = new LatLng(Double.parseDouble(split[0]),Double.parseDouble(split[1]));
            if(i==0){
                lat=latLng.latitude;
                lon=latLng.longitude;
            }
            latLngs.add(latLng);
        }
        // 设置当前地图显示为当前位置 缩放级别
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 18));
        aMap.addPolyline(new PolylineOptions().addAll(latLngs).width(20).color(Color.argb(255, 255, 255, 255)));
        if(historyData.getWorktype()==1){
            // 定义多边形的属性信息
            PolygonOptions polygonOptions = new PolygonOptions();
            // 添加多个多边形边框的顶点
            for (LatLng latLng : latLngs) {
                polygonOptions.add(latLng);
            }
            // 设置多边形的边框颜色，32位 ARGB格式，默认为黑色
            polygonOptions.strokeColor(Color.argb(0, 225, 225, 225));
            // 设置多边形的边框宽度，单位：像素
            polygonOptions.strokeWidth(5);
            // 设置多边形的填充颜色，32位ARGB格式
            polygonOptions.fillColor(Color.argb(100, 34, 139, 34)); // 注意要加前两位的透明度
            // 在地图上添加一个多边形（polygon）对象
            aMap.addPolygon(polygonOptions);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //初始化定位  用户合规检查
        AMapLocationClient.updatePrivacyShow(getContext(), true, true);
        AMapLocationClient.updatePrivacyAgree(getContext(), true);
        if (mapLayout == null) {
            mapLayout = inflater.inflate(R.layout.data_detail, null);
        }else {
            if (mapLayout.getParent() != null) {
                ((ViewGroup) mapLayout.getParent()).removeView(mapLayout);
            }
        }
        mapView = mapLayout.findViewById(R.id.measuremap);
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 设置卫星地图模式，aMap是地图控制器对象。
        //aMap.getUiSettings().setAllGesturesEnabled(false);//禁止地图可拖动
        //设置定位监听
        aMap.setLocationSource(this);
        //设置缩放级别
        //aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        //显示定位层并可触发，默认false
        aMap.setMyLocationEnabled(true);
        refresh();
        return mapLayout;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        if(locationClient==null){
            try {
                locationClient=new AMapLocationClient(getActivity());
                clientOption=new AMapLocationClientOption();
                locationClient.setLocationListener(this);
                clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//高精度定位
                //clientOption.setOnceLocationLatest(true);//设置单次精确定位
                locationClient.setLocationOption(clientOption);
                locationClient.startLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    @Override
    public void deactivate() {
        if(locationClient!=null){
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient=null;
    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
    }
    private void addMarker(boolean visible, List<LatLng> latLnglist) {
        ArrayList<MarkerOptions> options = new ArrayList<>();
        for (LatLng latLng : latLnglist) {
            // 在地图上添一组图片标记（marker）对象，并设置是否改变地图状态以至于所有的marker对象都在当前地图可视区域范围内显示
            MarkerOptions markerOptions = new MarkerOptions();
            // 设置Marker覆盖物的位置坐标。Marker经纬度坐标不能为Null，坐标无默认值
            markerOptions.position(latLng);
            // 设置Marker覆盖物是否可见
            markerOptions.visible(visible);
            // 设置Marker覆盖物是否可拖拽
            markerOptions.draggable(visible);
            options.add(markerOptions);
        }
        // 在地图上添一组图片标记（marker）对象，并设置是否改变地图状态以至于所有的marker对象都在当前地图可视区域范围内显示
        aMap.addMarkers(options, true);
    }
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if(isChecked){
            aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
        }
        else {
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        }
    }

}
